// 新增-修改广告页面
import React from 'react';
import {
  ScrollView, StyleSheet, View, TextInput, Dimensions
} from 'react-native';
import {
  Button, WhiteSpace, List, Toast
} from 'antd-mobile-rn';
import { NavigationActions } from 'react-navigation';
import BaseView from '../BaseView';
import { postSaveAD } from '../../model/ad';
import DatePicker from '../../components/DatePicker';
import ImagePicker from '../../components/ImagePicker';

export default class AdvertisementForm extends BaseView {
  constructor() {
    super();
    this.state = {
      adId: '',
      name: '',
      img: '232',
      star: '',
      end: '',
      files: []
    };
  }

  // 生命周期render前
  componentWillMount() {
    const { navigation, id } = this.props;
    const { adId } = this.state;
    navigation.setParams({ goback: this.goback.bind(this) });

    this.setState({
      adId: id
    });
    // 通过adId拉去页面数据
    if (adId) {
      alert('拉去页面数据');
      this.setState({
        name: '11',
        img:
          'https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=45e1c8e71ddfa9ece22e501752d1f754/342ac65c103853434cc02dda9f13b07eca80883a.jpg',
        time: '2015-02-12'
      });
    }
  }

  getTime(time) {
    const t = new Date(time);
    const y = t.getFullYear();
    const m = t.getMonth() + 1;
    const d = t.getDate();
    const h = t.getHours();
    const i = t.getMinutes();
    const s = t.getSeconds();
    // 可根据需要在这里定义时间格式
    return `${y}-${m < 10 ? `0${m}` : m}-${d < 10 ? `0${d}` : d} ${h < 10 ? `0${h}` : h}:${
      i < 10 ? `0${i}` : i
    }:${s < 10 ? `0${s}` : s}`;
  }

  componentDidMount() {
    super.componentDidMount();
    const { navigation } = this.props;
    navigation.setParams({
      title: navigation.getParam('id') ? '修改页面' : '新增页面',
      backgroundColor: '#3ca4d9',
      textColor: '#fff'
    });
  }

  // 上传照片
  imagesChange(filesName) {
    console.log(filesName);
    this.setState({
      files: filesName
    });
    // alert(files[0].url);
  }

  // 开始时间
  onChange(date) {
    this.setState({
      star: date
    });
  }

  // 结束时间
  onChange2(date) {
    this.setState({
      end: date
    });
  }

  goback() {
    const { navigation } = this.props;
    const backAction = NavigationActions.back();
    navigation.dispatch(backAction);
  }

  toAdList() {
    const { navigation } = this.props;

    const navigateAction = NavigationActions.navigate({
      routeName: 'Advertisement',
      params: {}
    });
    navigation.dispatch(navigateAction);
  }

  async gotoLogin(id, adname, files, star, end) {
    if (!adname) {
      alert('请输入广告标题');
      return false;
    }
    if (files.length === 0) {
      alert('请选择图片');
      return false;
    }
    if (!star) {
      alert('请选择开始时间');
      return false;
    }
    if (!end) {
      alert('请选择结束时间');
      return false;
    }
    const userInfo = await READ_CACHE('userInfo');

    try {
      await postSaveAD({
        terminalType: 'MOBILE',
        ad: {
          businessId: userInfo.id, // 商户ID
          name: adname, // 广告名称
          publicityPicture: files[0].url, // 宣传图片
          startTime: this.getTime(star), // 有效期开始时间
          endTime: this.getTime(end) // 有效期结束时间
        }
      });
      Toast.success('成功', 1);
      this.toAdList();
    } catch (e) {
      console.log(e);
    }

    return false;
    // 提交保存
  }

  render() {
    const {
      adId, name, star, end, files
    } = this.state;

    return (
      <ScrollView
        contentContainerStyle={advertisementForm.wrap}
        automaticallyAdjustContentInsets={false}
        showsHorizontalScrollIndicator={false}
        showsVerticalScrollIndicator={false}
      >
        <View style={advertisementForm.row}>
          <View style={advertisementForm.inputWrap}>
            <WhiteSpace size="lg" />
            <TextInput
              style={advertisementForm.input}
              placeholder="请输入广告名称"
              underlineColorAndroid="transparent"
              value={name}
              onChangeText={(text) => {
                this.setState({ name: text });
              }}
            />
            <WhiteSpace size="lg" />
            {/* <View style={advertisementForm.welcomeView}>
              <Image resizeMode="cover" source={{ uri: img }} style={advertisementForm.adimages} />
            </View> */}
            <View>
              <ImagePicker
                // selectButtonImageUrl="https://mxb-bucket.oss-cn-beijing.aliyuncs.com/232323232/1C8DD062-A12D-4074-A372-958DBCF234FA1531661598624233479IMG_0005.JPG"
                files={files}
                imageStyle={{
                  width: SCALE(576),
                  height: SCALE(176)
                }}
                selectable
                deletable
                max={1}
                containerStyle={{}}
                change={newFiles => this.imagesChange(newFiles)}
              />
            </View>
            <WhiteSpace size="lg" />
            <DatePicker
              style={advertisementForm.input}
              extra="请选择广告开始时间"
              value={star}
              mode="date"
              onChange={(date) => {
                this.onChange(date);
              }}
              format="YYYY-MM-DD"
            >
              <List.Item arrow="horizontal">Select Date</List.Item>
            </DatePicker>
            <WhiteSpace size="lg" />
            <DatePicker
              style={advertisementForm.input}
              extra="请选择广告结束时间"
              value={end}
              mode="date"
              onChange={(date) => {
                this.onChange2(date);
              }}
              format="YYYY-MM-DD"
            >
              <List.Item arrow="horizontal">Select Date</List.Item>
            </DatePicker>
          </View>
        </View>
        <WhiteSpace size="lg" />
        <Button
          type="primary"
          style={advertisementForm.btnWrap}
          onClick={() => {
            this.gotoLogin(adId, name, files, star, end);
          }}
        >
          提交审核
        </Button>
      </ScrollView>
    );
  }
}

const advertisementForm = StyleSheet.create({
  wrap: {
    flex: 1,
    alignItems: 'center'
  },
  content: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'center'
  },
  inputWrap: {
    width: SCALE(576)
  },
  input: {
    width: SCALE(576),
    height: SCALE(76),
    borderWidth: 1,
    borderColor: '#ccc',
    borderStyle: 'solid',
    borderRadius: 8,
    paddingRight: SCALE(30),
    paddingLeft: SCALE(30),
    backgroundColor: '#fff',
    position: 'relative'
  },
  btnWrap: {
    marginTop: SCALE(86),
    width: SCALE(576),
    height: SCALE(76),
    backgroundColor: '#044e8d',
    borderWidth: 0
  },
  welcomeView: {
    height: 136,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#045187'
  },
  adimages: {
    width: Dimensions.get('window').width,
    height: 136
  }
});
